#version 150

#moj_import <light.glsl>
#moj_import <fog.glsl>

in vec3 Position;
in vec4 Color;
in vec2 UV0;
in ivec2 UV2;
in vec3 Normal;

uniform sampler2D Sampler2;

uniform mat4 ModelViewMat;
uniform mat4 ProjMat;
uniform vec3 ChunkOffset;
uniform int FogShape;
uniform float GameTime;

out float vertexDistance;
out vec4 ssao;
out vec2 texCoord0;
out vec3 normal;
out vec4 ViewPosition;

bool check_float(float textureAlpha, float targetAlpha) {
	
	float targetLess = targetAlpha - 0.001;
	float targetMore = targetAlpha + 0.001;
	return (textureAlpha > targetLess && textureAlpha < targetMore);
}

float atan2(float y, float x)
{
	if(abs(x)>=abs(y))
	{
		float res = atan(y/x);
		if(x<0) res += 3.141;
		return res;
	}
	float res = atan(-1*x/y)+3.141/2;
	if(y<0) res += 3.141;
	return res;
}

void main() {
    vec3 pos = Position + ChunkOffset;
    normal = Normal;
    texCoord0 = UV0;
    ssao = Color * minecraft_sample_lightmap(Sampler2, UV2);

    //相关参数
    vec3 resPos;
    float phi = 3.141 * (0.5 - max(abs(fract(Position.x) - 0.5),abs(fract(Position.z) - 0.5)));
    float theta = (check_float(fract(Position.x),0.5)&&check_float(fract(Position.z),0.5))?0.0:atan2(fract(Position.z) - 0.5, fract(Position.x) - 0.5);

    //捕获特殊模型
    if(check_float(fract(Position.y),1.145/16.0)){//上表面
        normal = vec3(//法向量
            cos(phi) * cos(theta),
            sin(phi),
            cos(phi) * sin(theta)
        );
        resPos = vec3(//偏移坐标
            0.5 * normal.x + 0.5 - fract(Position.x),
            0.5 * normal.y,
            0.5 * normal.z + 0.5 - fract(Position.z)
        );
        pos += resPos;
        ssao = minecraft_sample_lightmap(Sampler2, UV2);
    }else if(check_float(fract(Position.y),1.045/16.0)){//下表面
        normal = vec3(//法向量
            cos(phi) * cos(theta),
            -1.0 * sin(phi),
            cos(phi) * sin(theta)
        );
        resPos = vec3(//偏移坐标
            0.5 * normal.x + 0.5 - fract(Position.x),
            0.5 * normal.y + 0.01,
            0.5 * normal.z + 0.5 - fract(Position.z)
        );
        pos += resPos;
        ssao = minecraft_sample_lightmap(Sampler2, UV2);
    }

    gl_Position = ProjMat * ModelViewMat * vec4(pos, 1.0);
    vertexDistance = fog_distance(pos, FogShape);
    ViewPosition = vec4(pos, 1.0);
}